import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';
import { message } from 'antd';
import { BASE_CONFIG } from './config';
import type { RequestConfig, ResponseData, RequestInterceptor, ResponseInterceptor } from './types';
import { useUserStore } from '@/stores/userStore';

class Request {
  private instance: AxiosInstance;
  private requestInterceptors: RequestInterceptor[] = [];
  private responseInterceptors: ResponseInterceptor[] = [];

  constructor(config: RequestConfig) {
    this.instance = axios.create({
      ...BASE_CONFIG,
      ...config,
    });

    // 添加请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 从 store 中获取 token
        const token = useUserStore.getState().token;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        // const { data } = response;

        // 处理业务状态码
        // if (data.code !== 200) {
        //   message.error(data.message || '请求失败');
        //   return Promise.reject(new Error(data.message || '请求失败'));
        // }
        return response;
      },
      (error) => {
        // 处理HTTP状态码
        if (error.response) {
          const { status } = error.response;
          switch (status) {
            case 401:
              // 未授权，清除 store 中的状态并跳转到登录页
              useUserStore.getState().logout();
              window.location.href = '/login';
              break;
            case 403:
              message.error('没有权限访问');
              break;
            case 404:
              message.error('请求的资源不存在');
              break;
            case 500:
              message.error('服务器错误');
              break;
            default:
              message.error('网络错误');
          }
        } else {
          message.error('网络错误，请检查您的网络连接');
        }
        return Promise.reject(error);
      }
    );
  }

  // 添加请求拦截器
  addRequestInterceptor(interceptor: RequestInterceptor) {
    this.requestInterceptors.push(interceptor);
    return this;
  }

  // 添加响应拦截器
  addResponseInterceptor(interceptor: ResponseInterceptor) {
    this.responseInterceptors.push(interceptor);
    return this;
  }

  // 请求方法
  async request<T = unknown>(config: RequestConfig): Promise<T> {
    try {
      // 应用请求拦截器
      let finalConfig = { ...config };
      for (const interceptor of this.requestInterceptors) {
        if (interceptor.onFulfilled) {
          finalConfig = interceptor.onFulfilled(finalConfig);
        }
      }

      // 发送请求
      const response = await this.instance.request<ResponseData<T>>(finalConfig);
      
      // console.log("response", response)
      // 应用响应拦截器
      let finalResponse = response;
      for (const interceptor of this.responseInterceptors) {
        if (interceptor.onFulfilled) {
          finalResponse = interceptor.onFulfilled(finalResponse) as AxiosResponse<ResponseData<T>>;
        }
      }

      // 处理成功消息
      if (config.showSuccess) {
        message.success(config.successMessage || '操作成功');
      }
      // console.log("finalResponse", finalResponse)
      return finalResponse.data as T;
    } catch (error: unknown) {
      // 处理错误消息
      if (config.showError !== false) {
        const errorMessage = error instanceof Error ? error.message : '请求失败';
        message.error(config.errorMessage || errorMessage || '请求失败');
      }

      // 应用错误拦截器
      for (const interceptor of this.responseInterceptors) {
        if (interceptor.onRejected) {
          return interceptor.onRejected(error) as Promise<ResponseData<T>>;
        }
      }

      throw error;
    }
  }

  // GET请求
  get<T = unknown>(url: string, config?: RequestConfig) {
    return this.request<T>({ ...config, method: 'GET', url });
  }

  // POST请求
  post<T = unknown>(url: string, data?: unknown, config?: RequestConfig) {
    return this.request<T>({ ...config, method: 'POST', url, data });
  }

  // PUT请求
  put<T = unknown>(url: string, data?: unknown, config?: RequestConfig) {
    return this.request<T>({ ...config, method: 'PUT', url, data });
  }

  // DELETE请求
  delete<T = unknown>(url: string, config?: RequestConfig) {
    return this.request<T>({ ...config, method: 'DELETE', url });
  }
}

// 创建请求实例
const request = new Request({});

export default request; 